/**
 * @file Common.c
 * @brief
 * @author F00
 * @date 2025-05-22
 */

#include "Common.h"

/******************************     Data Check    ************************************/

/**
 * @brief CRC32校验
 * 多项式: x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1
 * @param Buffer
 * @param Length
 * @return uint32_t
 */
uint32_t CRC32(uint8_t *Buffer, uint32_t Length)
{
    uint32_t CRC = 0xFFFFFFFF;

    for (uint32_t i = 0; i < Length; ++i)
    {
        CRC ^= Buffer[i];
        for (uint32_t Bit = 0; Bit < 8; ++Bit)
        {
            if ((CRC & 1) != 0)
            {
                CRC = (CRC >> 1) ^ 0xEDB88320;
            }
            else
            {
                CRC >>= 1;
            }
        }
    }

    return CRC;
}

/**
 * @brief CRC16校验
 * 多项式: x^16+x^12+x^5+1。
 * @param Buffer
 * @param Length
 * @return uint32_t
 */
uint16_t CRC16(uint8_t *Buffer, uint32_t Length)
{
    uint16_t CRC = 0xFFFF;
    for (uint32_t i = 0; i < Length; ++i)
    {
        CRC ^= Buffer[i];
        for (uint32_t Bit = 0; Bit < 8; ++Bit)
        {
            if ((CRC & 1) != 0)
            {
                CRC = (CRC >> 1) ^ 0xA001;
            }
            else
            {
                CRC >>= 1;
            }
        }
    }
    return CRC;
}

/**
 * @brief CRC8校验
 * 多项式: x^8+x^5+x^4+1
 * @param Buffer
 * @param Length
 * @return uint32_t
 */
uint8_t CRC8(uint8_t *Buffer, uint32_t Length)
{
    uint8_t CRC = 0xFF;

    for (uint32_t i = 0; i < Length; ++i)
    {
        CRC ^= Buffer[i];
        for (uint32_t Bit = 0; Bit < 8; ++Bit)
        {
            if ((CRC & 1) != 0)
            {
                CRC = (CRC >> 1) ^ 0x31;
            }
            else
            {
                CRC >>= 1;
            }
        }
    }
    return CRC;
}

/******************************     Data Check    ************************************/

/******************************       SysTick     ************************************/
// uint32_t SystemCoreClock = 160000000; // CPU频率 160MHz

/**
 * @brief 打印系统时钟
 */
void PrintSysTick(void)
{
    int64_t data = GetSysTick_us();
    uint16_t microseconds = data % 1000;
    uint16_t millisecond = data / 1000 % 1000;
    uint16_t second = data / 1000 / 1000 % 60;
    uint8_t minute = data / 1000 / 1000 / 60 % 60;
    uint8_t hour = data / 1000 / 1000 / 60 / 60 % 24;
    uint64_t day = data / 1000 / 1000 / 60 / 60 / 24;
    Printf("%lldd%02dh%02dm%02ds%03dms%03dus\r\n", day, hour, minute, second, millisecond, microseconds);
}

/******************************       SysTick     ************************************/